package com.lyl.goods.controller;

import com.lyl.goods.pojo.User;
import com.lyl.goods.service.AdminService;
import com.lyl.goods.utils.Md5Util;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import static com.lyl.goods.msg.Message.*;


@Controller
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;

/**
* @Description: 注册接口
* @Author: liyunlong
* @Date: 2024/3/1
*/
  
    @GetMapping("/register")
    public String showRegisterForm() {
        return "register"; // 假设返回到名为admin_register的视图模板
    }
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(@RequestParam("username")@Pattern(regexp = "^\\S{5,16}$") String username,
                           @RequestParam("password") @Pattern(regexp = "^\\S{5,16}$")String password, Model model, HttpSession session) {
        User user = adminService.find(username);
        if (user == null) {
            log.info("用户注册，注册用户名为：{}",username);
            adminService.registerAdmin(username, password);
            return "redirect:/login";
        } else {
            log.info(USER_EXITS);
            return "register";
        }
    }
    /**
    * @Description: 登录接口
    * @Author: liyunlong
    * @Date: 2024/3/1
    */
    @GetMapping("/login")
    public String showLoginForm() {
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestParam("username")@Pattern(regexp = "^\\S{5,16}$") String username,
                           @RequestParam("password")@Pattern(regexp = "^\\S{5,16}$") String password,HttpSession session) {
        User user = adminService.find(username);
        if (user == null) {
            log.info(USER_ERROR);
            return "login";
        }
        if (Md5Util.getMD5String(password).equals(user.getPassword()) && password != null) {
            log.info("管理员：{}，登录成功",username);
//            存userid
            session.setAttribute("userId",user.getId());
            session.setAttribute("currentUser", user.getUsername());
            return "redirect:/product";
        }
        else {
            log.info(PASSWORD_ERROR);
            return "login";
        }
    }
}
